/*
 * Project Beknyou
 * Copyright (c) 2010-2011 Saint Paul College, All Rights Reserved
 * Redistributions in source code form must reproduce the above
 * Copyright and this condition.
 * The contents of this file are subject to the GNU General Public
 * License, Version 2 (the "License"); you may not use this file
 * except in compliance with the License. A copy of the License is
 * available at http://www.opensource.org/licenses/gpl-license.php.
 */
package com.benkyou.server;

import com.benkyou.common.messages.WebcamMessage;
import com.benkyou.util.ByteArrayList;
import com.jme3.network.serializing.Serializer;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

/**
 *
 * @author Austin Allman
 */
public class WebcamServer {

    private Thread broadcast;
    private ByteArrayList bal;
    private URL imageUrl;
    private BufferedImage webImage;
    private ArrayList<byte[]> imageBytes = new ArrayList<byte[]>();
    private GameServer gameServer;

    public WebcamServer(GameServer gameServer) {
        Serializer.registerClass(WebcamMessage.class);
        this.gameServer = gameServer;
        bal = new ByteArrayList();
    }

    public void setupBroadcaster() {
        broadcast = new Thread(new Runnable() {

            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    try {

                        imageUrl = new URL("http://199.17.224.254/axis-cgi/jpg/image.cgi?resolution=640x480");//"http://199.17.224.254/axis-cgi/jpg/image.cgi?resolution=640x480");
                        webImage = ImageIO.read(imageUrl);
                        int imageID = (int) (Math.random() * 100);
                        byte[] bufferedImageBytes = getBufferedImageBytes(webImage);
                        if (bufferedImageBytes.length >= ByteArrayList.MESSAGE_LIMIT) {
                            imageBytes = bal.divideArrayList(ByteArrayList.MESSAGE_LIMIT, bufferedImageBytes);
                            int numberOfParts = imageBytes.size();
                            int imageCount = 0;
                            for (byte[] b : imageBytes) {
                                gameServer.getMyServer().broadcast(new WebcamMessage(b, numberOfParts, imageCount, imageID).setReliable(false));
                                ++imageCount;
                            }
                        } else {
                            int numberOfParts = -1;
                            int imageCount = -1;
                            gameServer.getMyServer().broadcast(new WebcamMessage(bufferedImageBytes, numberOfParts, imageCount, imageID).setReliable(false));
                        }

                    } catch (IOException ex) {
                        Logger.getLogger(WebcamServer.class.getName()).log(Level.SEVERE, null, ex);
                    }


                }
            }
        });

    }

    public byte[] getBufferedImageBytes(BufferedImage bufferedImage) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
        encoder.encode(bufferedImage);
        return os.toByteArray().clone();
    }

    public void startBroadcast() {
        broadcast.start();

    }

    public void stopBroadcast() {
        try {
            broadcast.interrupt();
        } catch (Exception e) {
        }
    }
}
